
package ch.hearc.coursJava.exa.swing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

import ch.hearc.coursJava.IO.persistence.objet.SerializeTools;

public class MainWindow extends JFrame
	{
	/**
     * 
     */
    private static final long serialVersionUID = -8982542268887693038L;


    /*------------------------------------------------------------------*\
	|*							Constructeurs							*|
	\*------------------------------------------------------------------*/
	public MainWindow()
		{
		this.isSave = false;
		creerItemMenu();
		creerMenu();

		this.setLocation(0, 0);
		this.setTitle("Table � dessin");
		this.setMinimumSize(new Dimension(800, 600));
		ImageIcon imageIcon= new ImageIcon("./img/icone.gif");
		this.icone = imageIcon.getImage();
		this.setIconImage(icone);

		creerPanels();
		placerPanels();
		creerToolbar();
		addListener();
		readSetting();

		this.thread.start();

		this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
		this.setVisible(true); //Par d�faut: NON-visible, A mettre en dernier
		}

	/*------------------------------------------------------------------*\
	|*							Methodes Public							*|
	\*------------------------------------------------------------------*/

	/*------------------------------*\
	|*				Get				*|
	\*------------------------------*/
	public boolean getIsSave()
		{
		return this.isSave;
		}

	public String getNomFichier()
		{
		return this.nomFichier;
		}

	/*------------------------------*\
	|*				Set				*|
	\*------------------------------*/
	public void setIsSave(boolean isSave)
		{
		this.isSave = isSave;
		}

	/*------------------------------------------------------------------*\
	|*							Methodes Private						*|
	\*------------------------------------------------------------------*/
	private void placerPanels()
		{
		BorderLayout borderLayout = new BorderLayout();
		setLayout(borderLayout);
		add(table, BorderLayout.CENTER);
		}

	private void creerPanels()
		{
		this.table = new TableDessin(this);
		this.thread = new Thread(table);

		}

	private void creerItemMenu()
		{
		this.itemQuitter = new JMenuItem("Quitter");
		this.itemQuitter.setMnemonic(KeyEvent.VK_Q);
		itemQuitter.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.ALT_MASK));

		this.itemEnregistrer = new JMenuItem("Enregistrer");
		this.itemQuitter.setMnemonic(KeyEvent.VK_E);
		itemEnregistrer.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.ALT_MASK));

		this.itemEnregistrerSous = new JMenuItem("Enregistrer sous");
		this.itemOuvrir = new JMenuItem("Ouvrir");
		this.itemBleu = new JMenuItem("Bleu");
		this.itemRouge = new JMenuItem("Rouge");
		}

	private void creerMenu()
		{
		this.menuBar = new JMenuBar();

		this.menuFichier = new JMenu("Fichier");
		menuFichier.setMnemonic(KeyEvent.VK_F);
		this.menuBar.add(menuFichier);

		this.menuEdition = new JMenu("Edition");
		this.menuCouleurs = new JMenu("Couleurs");
		this.menuCouleurs.add(itemBleu);
		this.menuCouleurs.add(itemRouge);
		this.menuEdition.add(menuCouleurs);
		this.menuBar.add(menuEdition);

		this.menuFichier.add(itemOuvrir);
		this.menuFichier.add(itemEnregistrer);
		this.menuFichier.add(itemEnregistrerSous);
		this.menuFichier.addSeparator();
		this.menuFichier.add(itemQuitter);

		this.setJMenuBar(menuBar);
		}

	private void creerToolbar()
		{
		this.toolBar = new JToolBar(SwingConstants.HORIZONTAL);
		this.toolBar.setFloatable(true);

		this.toolOpen = new JButton(new ImageIcon("./img/open.png"));
		this.toolBar.add(toolOpen);

		this.toolSave = new JButton(new ImageIcon("./img/save.png"));
		this.toolBar.add(toolSave);

		this.getContentPane().add(toolBar, BorderLayout.NORTH);
		}


	private void addListener()
		{
		itemQuitter.addActionListener(new ActionListener()
			{
				@Override
				public void actionPerformed(ActionEvent arg0)
					{
					processWindowEvent( new WindowEvent(MainWindow.this, WindowEvent.WINDOW_CLOSING));
					}
			});

		this.addWindowListener(new WindowAdapter()
			{
				@Override
				public void windowClosing(WindowEvent e)
					{
					if(!isSave)
						{
						int confirmation = JOptionPane.showConfirmDialog(null, "Voulez-vous enregistrer votre travail ?", "Confirmation", JOptionPane.YES_NO_OPTION);
						if(confirmation == JOptionPane.YES_OPTION)
							{
							if(nomFichier != null)
								{
								itemEnregistrer.doClick();
								}
							else
								{
								itemEnregistrerSous.doClick();
								}
							}
						writeSettings();
						System.exit(NORMAL);
						}
					else
						{
						int confirmation = JOptionPane.showConfirmDialog(null, "Voulez-vous vraiment quitter ?", "Confirmation", JOptionPane.YES_NO_OPTION);

						if(confirmation == JOptionPane.YES_OPTION)
							{
							writeSettings();
							System.exit(NORMAL);
							}
						}
					}
			});

		itemRouge.addActionListener(new ActionListener()
			{
				@Override
				public void actionPerformed(ActionEvent arg0)
					{
					table.setColor(Color.RED);
					table.repaint();
					}
			});

		itemBleu.addActionListener(new ActionListener()
			{
				@Override
				public void actionPerformed(ActionEvent arg0)
					{
					table.setColor(Color.BLUE);
					table.repaint();
					}
			});

		itemEnregistrerSous.addActionListener(new ActionListener()
			{
				@Override
				public void actionPerformed(ActionEvent arg0)
					{
					final JFileChooser fc = new JFileChooser();
					fc.addChoosableFileFilter(new BinFilter());
		            fc.setAcceptAllFileFilterUsed(false);


					//In response to a button click:
					int returnVal = fc.showSaveDialog(null);

					if(returnVal == JFileChooser.APPROVE_OPTION)
						{
						try
							{
							nomFichier = fc.getSelectedFile().toString();
							setTitle("Table � Dessin - "+nomFichier);
							File file = new File(fc.getSelectedFile().toString()+".bin");
							SerializeTools.saveBin(file, new Dessins(table.getListPoint()));
							removeStar();
							table.setStarWritted(false);
							isSave = true;
							}
						catch (Throwable e)
							{
							JOptionPane.showMessageDialog(null, "Erreur\n"+e.toString(), "Erreur", JOptionPane.OK_OPTION);
							}
						}
					else
						{

						}
					}
			});

		itemEnregistrer.addActionListener(new ActionListener()
			{
				@Override
				public void actionPerformed(ActionEvent e)
					{
					if(nomFichier != null)
						{
						try
							{
							SerializeTools.saveBin(new File(nomFichier), new Dessins(table.getListPoint()));

							removeStar();
							table.setStarWritted(false);
							isSave = true;
							}
						catch (Throwable e1)
							{
							JOptionPane.showMessageDialog(null, "Erreur\n"+e1.toString(), "Erreur", JOptionPane.OK_OPTION);
							}
						}
					else
						{
						itemEnregistrerSous.doClick();
						}
					}
			});

		itemOuvrir.addActionListener(new ActionListener()
			{
				@Override
				public void actionPerformed(ActionEvent arg0)
					{
					final JFileChooser fc = new JFileChooser();
					fc.addChoosableFileFilter(new BinFilter());
		            fc.setAcceptAllFileFilterUsed(false);

					int returnVal = fc.showOpenDialog(null);

					if(returnVal == JFileChooser.APPROVE_OPTION)
						{
						try
							{
							nomFichier = fc.getSelectedFile().toString();
							setTitle("Table � Dessin - "+nomFichier);
							Dessins dessin = (Dessins)SerializeTools.loadBin(fc.getSelectedFile());
							table.setListPoint(dessin.getListPoint());
							table.repaint();
							}
						catch (Throwable e)
							{
							JOptionPane.showMessageDialog(null, "Erreur\n"+e.toString(), "Erreur", JOptionPane.OK_OPTION);
							}
						}
					}
			});

		toolOpen.addActionListener(new ActionListener()
			{
				@Override
				public void actionPerformed(ActionEvent arg0)
					{
					itemOuvrir.doClick();
					}
			});

		toolSave.addActionListener(new ActionListener()
			{
				@Override
				public void actionPerformed(ActionEvent arg0)
					{
					itemEnregistrer.doClick();
					}
			});
		}

	private void writeSettings()
		{
		Properties properties = new Properties();
		properties.setProperty("positionX", new Integer(getX()).toString());
		properties.setProperty("positionY", new Integer(getY()).toString());
		properties.setProperty("width", new Integer(getWidth()).toString());
		properties.setProperty("height", new Integer(getHeight()).toString());

		try
			{
			PROPERTIES_FILE.getParentFile().mkdirs();
			FileOutputStream fileOutputStream = new FileOutputStream(PROPERTIES_FILE);
			BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
			properties.store(bufferedOutputStream, MainWindow.class.getSimpleName());

			bufferedOutputStream.close();
			fileOutputStream.close();
			}
		catch (Exception e)
			{
			JOptionPane.showMessageDialog(null, "Impossible d'enregistrer les propri�t�s du programme !\n"+e.toString(), "Erreur", JOptionPane.OK_OPTION);
			}
		}

	private void readSetting()
		{
		Properties properties = new Properties();
		try
			{
			FileInputStream fileInputStream = new FileInputStream(PROPERTIES_FILE);
			BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
			properties.load(bufferedInputStream);
			int x = Integer.valueOf(properties.getProperty("positionX", "5"));
			int y = Integer.valueOf(properties.getProperty("positionY", "20"));
			int h = Integer.valueOf(properties.getProperty("height", "600"));
			int w = Integer.valueOf(properties.getProperty("width", "800"));

			setLocation(x, y);
			setSize(w, h);

			bufferedInputStream.close();
			fileInputStream.close();
			}
		catch (Exception e)
			{
			JOptionPane.showMessageDialog(null, "Impossible de lire les propri�t�s !\n"+e.toString(), "Erreur", JOptionPane.OK_OPTION);
			}
		}

	private void removeStar()
		{
		String title = getTitle();
		if(title.charAt(title.length() - 1) == '*')
			{
			setTitle(title.substring(0, title.length() - 2));
			}
		}

	/*------------------------------------------------------------------*\
	|*							Attributs Private						*|
	\*------------------------------------------------------------------*/
	//tools
	private Image icone;
	private TableDessin table;
	private Thread thread;
	private boolean isSave;
	private String nomFichier;

	//tools menu
	private JMenuBar menuBar;

	private JMenu menuFichier;
	private JMenu menuEdition;
	private JMenu menuCouleurs;

	private JMenuItem itemQuitter;
	private JMenuItem itemOuvrir;
	private JMenuItem itemEnregistrer;
	private JMenuItem itemEnregistrerSous;
	private JMenuItem itemBleu;
	private JMenuItem itemRouge;

	//tools toolBar
	private JToolBar toolBar;
	private JButton toolOpen;
	private JButton toolSave;


	/*------------------------------*\
	|*			  Static			*|
	\*------------------------------*/
	private static final File PROPERTIES_FILE = new File("config" + File.separator + MainWindow.class.getSimpleName());

	}

